package com.gkj.blog.business.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gkj.blog.business.service.RoleService;
import com.gkj.blog.business.vo.condition.RoleConditionVO;
import com.gkj.blog.business.vo.entity.Role;
import com.gkj.blog.framework.object.AbstractServiceImpl;
import com.gkj.blog.persistence.mapper.SysRoleMapper;
import com.gkj.blog.persistence.mapper.SysRoleResourcesMapper;
import com.gkj.blog.persistence.po.SysRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Service
public class RoleServiceImpl extends AbstractServiceImpl<Role,SysRole> implements RoleService {

    SysRoleMapper sysRoleMapper;

    @Autowired
    SysRoleResourcesMapper sysRoleResourcesMapper;

    @Autowired
    public void setSysRoleMapper(SysRoleMapper sysRoleMapper) {
        this.sysRoleMapper = sysRoleMapper;
        setBaseMapper(sysRoleMapper);
    }

    @Override
    public PageInfo<Role> findPageBreakByCondition(RoleConditionVO vo) {
        PageHelper.startPage(vo.getPageNumber(), vo.getPageSize());
        List<SysRole> sysRoles = sysRoleMapper.findPageBreakByCondition(vo);
        if (CollectionUtils.isEmpty(sysRoles)) {
            return null;
        }
        List<Role> roles = new ArrayList<>();
        for (SysRole r : sysRoles) {
            roles.add(new Role(r));
        }
        PageInfo bean = new PageInfo<SysRole>(sysRoles);
        bean.setList(roles);
        return bean;
    }

    @Override
    public List<Role> queryRoleListWithSelected(Integer uid) {
        List<SysRole> sysRoles = sysRoleMapper.queryRoleListWithSelected(uid);
        List<Role> roles=new LinkedList<>();
        sysRoles.forEach((e)->{
            roles.add(new Role(e));
        });
        return roles;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeRoleAndRelation(Long[] ids) {
        if(ids==null||ids.length==0)
            return false;
        for (Long id : ids) {
            sysRoleMapper.deleteByPrimaryKey(id);
            sysRoleResourcesMapper.removeByRoleId(id);
        }
        return true;
    }
}
